package org.openkanban.client.ui.presenter;

import org.openkanban.client.Main;
import org.openkanban.client.login.LogIn;
import org.openkanban.client.util.RootPanel;
import org.openkanban.shared.dto.UserDto;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.smartgwt.client.types.AnimationEffect;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.AnimationCallback;

/**
 * Callback that handles log in request
 */
public class LogInRequestCallback implements RequestCallback {

    @Override
    public void onError(Request request, Throwable exception) {
	SC.say("ERROR: " + exception.getMessage());
    }

    @Override
    public void onResponseReceived(Request request, Response response) {
	if (response.getStatusCode() == 200) {
	    RootPanel.main.getAdminPanel().getLoginForm().getMessage().hide();
	    RootPanel.main.getAdminPanel().getVsLoginVStack().animateHide(AnimationEffect.SLIDE, new AnimationCallback() {
		@Override
		public void execute(boolean earlyFinish) {
		    RootPanel.main.getAdminPanel().getLoginForm().reset();
		}
	    }, 250);
	    final UserDto userDto = new UserDto(response.getText());
	    RootPanel.main.getVlMain().animateHide(AnimationEffect.FADE, new AnimationCallback() {
		@Override
		public void execute(boolean earlyFinish) {
		    LogIn.setLoggedInUser(userDto);
		    LogIn.processLogIn();
		    RootPanel.main.getVlMain().animateShow(AnimationEffect.FADE, null, Main.DEFAULT_FADE_DURATION);
		}
	    }, Main.DEFAULT_FADE_DURATION);
	} else {
	    RootPanel.main.getAdminPanel().getLoginForm().getMessage().show();
	}
    }
}
